<?php

/*
	小游戏安装与更新
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'installed';
$manage_op=array('uninstall','update');
if(in_array($_RQ['op'],$manage_op)){
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择小游戏！','error');
	}
	$plugin=pdo_get('core_h5game',array('id'=>$id));
	if(!$plugin){
		exi('指定小游戏不存在！','error');
	}
}
//检查是否安装互动营销活动模块
$check=pdo_getcolumn('core_plugins',array('name'=>'jy_h5game'),'id');
if(!$check){
	exi('请先安装互动营销活动插件！才能使用小游戏功能！','error','core/cloud.module/prepared');
}
$return=array();
$tabs=array(
	array('op'=>'installed','title'=>'小游戏列表'),
	array('op'=>'updates','title'=>'待更新小游戏'),
	array('op'=>'prepared','title'=>'待安装小游戏'),
);
$types=array(
	'1'=>'节日活动',
	'2'=>'抽奖活动',
	'3'=>'游戏营销',
	'4'=>'助力活动',
	'5'=>'投票活动',
	'6'=>'签到活动',
);

if($_RQ['op'] == 'installed'){
	
	$_AR['page']['title'] = '小游戏列表';
	$params=array();
	if($_RQ['type']){
		$params['type']=intval($_RQ['type']);
		$return['params']['type']=$_RQ['type'];
	}
	if(!empty($_RQ['title'])){
		$params['title like']='%'.trim($_RQ['title']).'%';
		$return['params']['title']=$_RQ['title'];
	}
	$orderby='id desc';
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$total='';
	$fields=array('id','type','release','image','version','name','title');
	$list=pdo_getslice('core_h5game',$params,array($pindex,$psize),$total,$fields,'',$orderby);
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['types']=$types;
	$return['htmls']=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已安装小游戏列表','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
			array('name'=>'image','title'=>'小游戏logo','type'=>'image'),
			array('name'=>'type','title'=>'小游戏类型','type'=>'radio','options'=>'types'),
			array('name'=>'title','title'=>'小游戏名称','type'=>'string'),
			array('name'=>'name','title'=>'小游戏标识','type'=>'string'),
			array('name'=>'version','title'=>'小游戏版本','type'=>'string'),
			array('name'=>'release','title'=>'版本日期','type'=>'time'),
		),'action'=>array(
			array('type'=>'post','op'=>'uninstall','title'=>'卸载','message'=>'卸载将删除该小游戏的文件和数据，且不可恢复！确认卸载吗！'),
		)),
		'search_one'=>array('name'=>'title','add'=>false,'select_name'=>'type','is_radio'=>true,'options'=>'types','select_title'=>'全部'),
	);
	exi($return);
}

if ($_RQ['op'] == 'uninstall'){
	pdo_delete('core_h5game',array('id'=>$plugin['id']));
	exi('卸载成功！');
}
if($_RQ['op'] == 'updates') { 
	//待更新组件列表，此处显示所有待更新的组件
	$params=array();
	$fields=array('id','cloud_id','title','version','release','image');
	$list=pdo_getall('core_h5game',$params,$fields,'cloud_id');
	if($list){
		$cloud_ids=array_keys($list);
		$cloud_ids=implode(';',$cloud_ids);
		$post=array('cloud_ids'=>$cloud_ids);
		$versions=cloud_request('update.h5game.getup',$post);
		foreach($versions as $name=>$version){
			if($version['version']==$list[$name]['version']){
				//去掉无需更新的小游戏
				unset($list[$name]);
			}else{
				$list[$name]['new_version']=$version['version'];
				//$list[$name]['new_release']=$version['release'];
			}
		}
	}
	$return['list']=$list;
	$return['types']=$types;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'更新存在新版本的功能小游戏','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'image','title'=>'小游戏logo','type'=>'image'),
			array('name'=>'type','title'=>'小游戏类型','type'=>'radio','options'=>'types'),
			array('name'=>'title','title'=>'小游戏名称','type'=>'string'),
			array('name'=>'version','title'=>'当前版本','type'=>'string'),
			array('name'=>'new_version','title'=>'最新版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'href','op'=>'update','title'=>'更新'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'info'){
	//前往小游戏商城查看更新说明，在新窗口打开更新说明页面。
	$url='http://s.jinyunweb.com';
	exi('','','',$url);
}
if($_RQ['op'] == 'update') {
	//更新小游戏
	$dir = ROOT_PLUGIN.'jy_h5game/custom/templates/mobile/games/'.$plugin['name'];
	if(!$_SESSION['download'] || !is_file(ROOT_AT.$plugin['name'].'.update')){
		$post=array('cloud_id'=>$plugin['cloud_id']);
		
		$dat=cloud_request('update.h5game.build',$post);
		//更新文件
		$upfiles=$files = array();
		if(!empty($dat['files'])) {
			$mdir=ROOT_AT .'module_baks/'.$plugin['name'];
			if(!is_dir($mdir)){
				cfc('files')->mkdirs($mdir);
			}
			$bak = $mdir.'/'.$plugin['version'].'.'.TIMESTAMP;
			$zip= new ZipArchive();
			$zip->open($bak, ZipArchive::CREATE);
			foreach($dat['files'] as $file) {
				$entry = $dir . $file['path'];
				if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
					$files[] =$file['path'];
					$upfiles[]=$file;
				}
				if(is_file($entry) && md5_file($entry) != $file['checksum']) {
					$zip->addFile($entry,$file['path']);
				}
			}
			$zip->close();
		}
		//检查文件权限
		if(!empty($files)){
			$error=array();
			foreach($files as $f){
				$path = ROOT_PLUGIN.$plugin['name'].$f;
				if(file_exists($path)){
					if(!is_writable($path)){
					 $error[]=$path.'文件没有写入的权限';
					}
				}else{
					$path=get_dirname($path);
					if(!is_writable($path)){
					$error[]=$path.'文件夹没有写入的权限';
					}
				}
			}
			if($error){
				$error=implode(';',$error);
				exi($error,'error');
			}
		}
	
		if(!empty($files)){
			$post=array('cloud_id'=>$plugin['cloud_id'],'files'=>$files);
			$files=cloud_request('update.h5game.getmodule',$post);
			//下载更新文件时，如果内容较少，则一次性下载之，否则跳转下载页分批下载
			if($files['parts']==1){
				$data=cloud_request('update.download',array('id'=>$files['id'],'part'=>1),true);
				file_put_contents(ROOT_AT.$plugin['name'].'.update',$data);
			}else{
				$_SESSION['download']=array(
					'id'=>$files['id'],
					'parts'=>$files['parts'],
					'to'=>$plugin['name'].'.update',
				);
				cache_write($plugin['name'].'.update',$dat);
				exi('准备下载更新文件！','success','core/cloud.download/');
			}
		}
	}
	if(is_file(ROOT_AT.$plugin['name'].'.update')){
		$zip = new ZipArchive();
		$zip->open(ROOT_AT.$plugin['name'].'.update');
		$zip->extractTo($dir);
		$zip->close();
		@unlink(ROOT_AT.$plugin['name'].'.update');
		
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	if(!$dat){
		$dat=cache_read($plugin['name'].'.update');
		cache_delete($plugin['name'].'.update');
	}
	//检测文件是否更新成功
	if($upfiles){
		foreach($upfiles as $file) {
			$entry = $dir . $file['path'];
			if(!is_file($entry) || md5_file($entry) != $file['checksum']) {
				exi("更新失败，请设置好小游戏根目录（".$dir."）的权限再更新！",'error');
			}
		}
	}
	//更新其他
	$data=array_fields(array('title','version','type','release','desc','image'),$dat);
	if($dat['image']){
		$image=file_get_contents($dat['image']);
		$data['image']=cfc('files')->source_save($image,'image','jpg','小游戏“'.$dat['title'].'”logo');
	}
	pdo_update('core_h5game',$data,array('id'=>$id));
	exi('更新成功！','','goback');
}
if($_RQ['op'] == 'prepared'){
	$_AR['page']['title'] = '待安装小游戏列表';
	
	$plugins = pdo_getall('core_h5game',array(),array('cloud_id'),'cloud_id');
	$plugins=array_keys($plugins);
	$result=cloud_request('update.h5game.getbuyed',array('plugins'=>$plugins));
	$return['list']=$result;
	$return['types']=$types;
	$htmls=array(
		'type'=>'list',
		'tabs'=>$tabs,
		'list'=>array('tip'=>'已购买但尚未安装的小游戏。安装大小游戏时，可能需要等长一点时间，请耐心等待，不要重复点击。','data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'pagelist'=>false,'list'=>array(
			array('name'=>'image','title'=>'小游戏logo','type'=>'image'),
			array('name'=>'type','title'=>'小游戏类型','type'=>'radio','options'=>'types'),
			array('name'=>'title','title'=>'小游戏名称','type'=>'string'),
			array('name'=>'version','title'=>'小游戏版本','type'=>'string'),
		),'action'=>array(
			array('type'=>'href','op'=>'install','title'=>'安装'),
		)),
		'search_one'=>array('name'=>'title','add'=>false),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op'] == 'install') {
	//安装小游戏
	$id=intval($_RQ['id']);
	if(!$id){
		exi('请先选择要安装的小游戏！','error');
	}
	if(!$_SESSION['download'] || !is_file(ROOT_AT.$id.'.install')){
		if (pdo_getcolumn('core_h5game',array('cloud_id'=>$id),'id')) {
			exi('小游戏已经安装或是唯一标识已存在！','error');
		}
		if(is_file(ROOT_AT.$id.'.install')){
			@unlink(ROOT_AT.$id.'.install');
		}
		//获取小游戏基本数据
		$post=array('cloud_id'=>$id);
		$module=cloud_request('update.h5game.install',$post);
		
		if($module['files']['parts']==1){
			$install_data=cloud_request('update.download',array('id'=>$module['files']['id'],'part'=>1),true);
			file_put_contents(ROOT_AT.$id.'.install',$install_data);
		}else{
			//将小游戏数据保存到临时文件中，开始下载文件
			$config=serialize($module);
			file_put_contents(ROOT_AT.$id.'.config',$config);
			$_SESSION['download']=array(
				'id'=>$module['files']['id'],
				'parts'=>$module['files']['parts'],
				'to'=>$id.'.install',
			);
			exi('准备下载安装文件！','','core/cloud.download/');
		}
	}
	if(!$module){
		$module=file_get_contents(ROOT_AT.$id.'.config');
		$module=unserialize($module);
		@unlink(ROOT_AT.$id.'.config');
	}
	if(is_file(ROOT_AT.$id.'.install')){
		if($module['md5'] && md5_file(ROOT_AT.$id.'.install')!=$module['md5']){
			@unlink(ROOT_AT.$id.'.install');
			exi('文件校验出错，可能是网络不稳定导致，请稍后尝试重新下载！','error','goback');
		}
		$zip = new ZipArchive();
		$zip->open(ROOT_AT.$id.'.install');
		$zip->extractTo(ROOT_PLUGIN.'jy_h5game/custom/templates/mobile/games/'.$module['name']);
		$zip->close();
		@unlink(ROOT_AT.$id.'.install');
	}
	if($_SESSION['download']){
		unset($_SESSION['download']);
	}
	$data=array_fields(array('name','title','type','version','release'),$module);
	if($module['image']){
		$image=file_get_contents($module['image']);
		$data['image']=cfc('files')->source_save($image,'image','jpg','小游戏“'.$module['title'].'”logo');
	}
	$data['cloud_id']=$id;
	pdo_insert('core_h5game',$data);
	exi('安装成功！','','installed');
}
function get_dirname($file){
	$dir=dirname($file);
	if(!is_dir($dir)){
		$dir=get_dirname($dir);
	}
	return $dir;
}